package com.pipi.sso.core.service.impl;

import com.google.common.collect.Lists;
import com.pipi.sso.core.enums.CommonStatusEnum;
import com.pipi.sso.core.model.MenuBO;
import com.pipi.sso.core.service.MenuService;
import com.pipi.sso.core.util.BeanUtils;
import com.pipi.sso.dao.manager.MenuManager;
import com.pipi.sso.dao.model.MenuDO;
import com.pipi.sso.dao.query.MenuQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * All rights Reserved, Designed By www.maihaoche.com
 *
 * @Package com.pipi.sso.core.service.impl
 * @date: 2019/3/30 5:44 PM
 * @Copyright: 2017-2020 www.maihaoche.com Inc. All rights reserved.
 */
@Service
@Slf4j
public class MenuSerivceImpl implements MenuService {

    @Resource
    private MenuManager menuManager;

    @Override
    public List<MenuBO> queryAllMenu() {
        MenuQuery menuQuery = new MenuQuery();
        menuQuery.setOrderByClause("order_num asc");
        menuQuery.createCriteria().andIsDeletedEqualTo(CommonStatusEnum.NO.getCode());
        // 查询出所有未删除的菜单
        List<MenuDO> menuDOS = menuManager.selectByQuery(menuQuery);
        List<MenuBO> menuBOS = menuDOS.stream().map(menuDO -> BeanUtils.createCloneBean(menuDO, MenuBO.class)).collect(Collectors.toList());
        // 过滤出一级菜单
        Map<Long, MenuBO> firstMenuBOMap = menuBOS.stream().filter(menuBO -> menuBO.getMenuType().equals(1))
                .collect(Collectors.toMap(MenuBO::getMenuId, Function.identity()));
        // 过滤出二级菜单
        List<MenuBO> secondMenu = menuBOS.stream().filter(menuBO -> menuBO.getMenuType().equals(2)).collect(Collectors.toList());
        // 将二级菜单关联到一级菜单
        for (MenuBO menu : secondMenu) {
            Long parentId = menu.getParentId();
            firstMenuBOMap.get(parentId).getChildrenMenu().add(menu);
        }
        return Lists.newArrayList(firstMenuBOMap.values());
    }
}
